<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert
        title="编辑商品信息"
        type="info"
        :closable="false"
        show-icon
        center
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab区域 -->
      <el-form
        :model="updateGoodsForm"
        :rules="updateGoodsRules"
        ref="updateGoodsRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          style="height: 100%"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="updateGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="updateGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="updateGoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="updateGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="parentCateList"
                :props="parentCateProps"
                v-model="updateGoodsForm.goods_cat"
                @change="parentCateChanged"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_value">
                <el-checkbox
                  :label="vals"
                  v-for="(vals, i) in item.attr_value"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_value"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action标识图片要上传到的后台api地址 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="uploadPreview"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="updateGoodsForm.goods_introduce"
              ref="myQuillEditor"
              :options="editorOption"
            >
            </quill-editor>
            <!-- 添加商品 -->
            <el-button type="primary" class="btnupdate" @click="updateGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="preview_dialogVisible"
      width="30%"
    >
      <img
        :src="previewUrl"
        alt=""
        class="previewImg"
      />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      updateGoodsForm: {},
      updateGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
      },
      //  父级分类列表
      parentCateList: [],
      // 级联选择器的配置属性
      parentCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      manyTabData: [],
      onlyTabData: [],
      selectedKeys: [],
      //   上传图片的url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   图片上传组件的header请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      previewUrl: '',
      preview_dialogVisible: false,
      editorOption: {},
      attrs: [],
    }
  },
  created() {
    this.getParentCateList()
    this.getGoodsById()
  },
  methods: {
    // 获取商品分类数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取父级分类失败')
      this.parentCateList = res.data
    },
    // 商品父级分类的改变
    parentCateChanged() {
      if (this.updateGoodsForm.goods_cat.length !== 3) {
        this.updateGoodsForm.goods_cat = []
        return
      }
    },
    // 切换tab之前先选择商品分类
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.updateGoodsForm.goods_cat === ' ') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //tab动态参数和静态属性切换
    async tabClick() {},
    // 处理图片预览效果
    uploadPreview(file) {
      this.previewUrl = file.response.data.url
      this.preview_dialogVisible = true
    },
    // 处理移除图片的操作
    uploadRemove(file) {
      // 需要删除的url
      const removUrl = file.response.data.tmp_path
      const index = this.updateGoodsForm.pics.findIndex(
        (x) => x.pic === removUrl
      )
      this.updateGoodsForm.pics.splice(index, 1)
    },
    // 监听图片上传成功的事件
    uploadSuccess(res) {
      // if(res.data.status!==200) return this.$message.error("上传失败")
      // 1.拼接得到图片信息对象
      const picInfo = { pic: res.data.tmp_path }
      // 2.将图片对象push到pics数组中
      this.updateGoodsForm.pics.push(picInfo)
      // console.log( this.updateGoodsForm);
    },
    async getGoodsById() {
      // console.log(this.$route.params.goods_id);
      const goodsId = this.$route.params.goods_id
      // console.log(goodsId);
      const { data: res } = await this.$http.get('goods/' + goodsId)
      if (res.meta.status !== 200)
        return this.$message.error('获取商品信息失败')
      this.updateGoodsForm = res.data
      // 执行添加到请求
      // const form = _.cloneDeep(this.updateGoodsForm)
      // 选择商品分类赋值
      this.updateGoodsForm.goods_cat = this.updateGoodsForm.goods_cat
        .split(',')
        .map(Number)
      // console.log(res)
      this.updateGoodsForm.attrs.forEach((item) => {
        // console.log(item.attr_sel);
        // 为动态静态参数赋值
        if (item.attr_sel === 'only') {
          this.onlyTabData.push(item)
        } else {
          // console.log(item);
          item.attr_value = item.attr_value.split(' ')
          this.manyTabData.push(item)
        }
      })
    },
    // 添加商品
    updateGoods() {
      // console.log(this.updateGoodsForm)
      this.$refs.updateGoodsRef.validate(async (data) => {
        if (!data) return this.$message.error('请填写必要的表单项')
        // 执行添加到请求
        const form = _.cloneDeep(this.updateGoodsForm)
        // 拼接成字符串
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTabData.forEach((item) => {
          const attrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_value.join(' '),
          }
          this.attrs.push(attrsInfo)
        })
        // 处理静态属性
        this.onlyTabData.forEach((item) => {
          const attrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_value,
          }
          this.attrs.push(attrsInfo)
        })
        // form.attrs = this.updateGoodsForm.attrs
        // console.log(this.updateGoodsForm);
        // console.log(form);
        // 发起请求,商品名称是唯一的
        const { data: res } = await this.$http.put(
          'goods/' + this.updateGoodsForm.goods_id,
          {
            goods_name: this.updateGoodsForm.goods_name,
            goods_price: this.updateGoodsForm.goods_price,
            goods_number: this.updateGoodsForm.goods_number,
            goods_weight: this.updateGoodsForm.goods_weight,
            goods_introduce: this.updateGoodsForm.goods_introduce,
            goods_cat: form.goods_cat,
            pics: this.updateGoodsForm.pics,
            attrs: this.attrs,
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('编辑商品失败')
        this.$message.success('编辑商品成功')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.updateGoodsForm.goods_cat.length === 3) {
        return this.updateGoodsForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-upload__tip {
  font-size: 13px;
}
.previewImg {
  width: 100%;
}
.btnupdate {
  margin-top: 15px;
}
</style>